<template>
	<view class='contents'>
		<view id='myCanvas' class='myCanvas'>
			<div style='width:90%;margin:0 auto;' id="pagePoster" class="my" ref="pagePoster">
				<!-- <view
					style='width:100%;text-align: center;font-size: 30rpx;font-weight: bold;height:100rpx;line-height: 100rpx;'>
					规则</view> -->
				<view class="imgs" style='font-size: 28rpx;line-height: 48rpx;'>
					<!-- <image class="img" :src="img" mode="widthFix"></image> -->
				</view>
				<view class="fle">
					<view class="btn"></view>
					<view
						style='text-align: center;font-size: 26rpx;width:200rpx;height:70rpx;line-height: 70rpx;background-color: #3C8EFF;color:#FFFFFF;border-radius: 40rpx;margin:0 auto;margin-top:20rpx;'
						@click='showSign(1)'>患者姓名+手机号</view>

					<view
						style='text-align: center;font-size: 26rpx;width:200rpx;height:70rpx;line-height: 70rpx;background-color: #3C8EFF;color:#FFFFFF;border-radius: 40rpx;margin:0 auto;margin-top:20rpx;'
						@click='showSign(2)'>
						<text>护士签名</text>
					</view>

					<view v-if="!signImage"
						style='text-align: center;font-size: 26rpx;width:200rpx;height:70rpx;line-height: 70rpx;background-color: #3C8EFF;color:#FFFFFF;border-radius: 40rpx;margin:0 auto;margin-top:20rpx;'
						@click='handleComplete(1)'>用户无法签名</view>
					<view class="aa">
						<view v-if="signImage&&nurseImage "
							style='text-align: center;font-size: 26rpx;width:200rpx;height:70rpx;line-height: 70rpx;background-color: #3C8EFF;color:#FFFFFF;border-radius: 40rpx;margin:0 auto;margin-top:20rpx;'>
							开始服务</view>
						<view class="mybtn" @click="canvasImage.generateImage"></view>
					</view>

				</view>
				<view v-if='signImage' style='text-align: right;'>
					用户签名：<image :src='signImage' style='width:200rpx;height:100rpx;'></image>
				</view>
				<view v-if='signImage' style='text-align: right;'>
					签署时间：<text>{{gettime}}</text>
				</view>
				<view v-if='nurseImage' style='text-align: right;'>
					护士签名：<image :src='nurseImage' style='width:200rpx;height:100rpx;'></image>
				</view>

			</div>
		</view>
		<myPopup ref="pop">
			<view style='background-color: #FFFFFF;border-top-left-radius: 20rpx;border-top-right-radius: 20rpx;'>
				<view
					style='margin-left:92%;margin-top:30rpx;width:40rpx;height:40rpx;font-size: 26rpx;line-height: 40rpx;background-color: #000000;opacity: 0.5;border-radius: 20rpx;text-align: center;position:fixed;z-index:3000;right:20rpx;color:#FFFFFF'
					@click='hideShow'>X</view>
				<view
					style='width:100%;height:100rpx;line-height: 100rpx;font-size: 30rpx;font-weight: bold;text-align: center;'>
					开始签名</view>
				<canvas class='firstCanvas' canvas-id="firstCanvas" @touchmove='move' @touchstart='start($event)'
					@touchend='end' @touchcancel='cancel' @longtap='tap' disable-scroll='true' @error='error'>
				</canvas>

				<view class="caozuo">
					<view class="chongqian" @tap='clearClick'>
						重签
					</view>
					<view class="over" @click="overSign">
						完成签名
					</view>
				</view>
			</view>
		</myPopup>
		<image :src='imgData' style='width:100rpx;height:200rpx;'></image>
	</view>
</template>

<script>
	import { httpUrl } from '@/utils/options.js'
	import uploadImage from '@/common/js/ossutil/uploadFile.js'
	import {
		signDisclaimer
	} from '@/apis/order/index.js'
	import html2canvas from 'html2canvas'
	import base64ToPath from 'image-tools'
	var content = null
	var touchs = []
	var canvasw = 0
	var canvash = 0
	var _that
	//获取系统信息
	uni.getSystemInfo({
		success: function(res) {
			canvasw = res.windowWidth
			canvash = res.windowHeight
		},
	})
	import myPopup from '@/components/common/qianxiao-pop.vue'
	export default {
		components: {
			myPopup,
		},
		data() {
			return {
				signImage: '',
				nurseImage: '',
				// 最终的图
				myImg: '',
				imgData: '',
				isEnd: false, // 是否签名，
				isSign: 1, //0 无法签署  1.可以签署
				number: '',
				type: 1, //护士签名
				gettime: '',
			}
		},
		/**
		 * 生命周期函数--监听页面加载
		 */
		onLoad: function(options) {
			if (options.number) {
				this.number = options.number
				this.img = options.img
			}
			_that = this
			//获得Canvas的上下文
			content = uni.createCanvasContext('firstCanvas', _that)
		},

		methods: {
			renderFinish(filePath) {
				this.imgData = filePath
				this.saveHeadImgFile(filePath)
				return
			},
			saveHeadImgFile(urls) {
				let base64 = urls
				const bitmap = new plus.nativeObj.Bitmap('test')
				bitmap.loadBase64Data(
					base64,
					function() {
						const url = '_doc/' + new Date().getTime() + '.png' // url为时间戳命名方式
						console.log('saveHeadImgFile', url)
						bitmap.save(
							url, {
								overwrite: true, // 是否覆盖
								// quality: 'quality'  // 图片清晰度
							},
							(i) => {
								uni.saveImageToPhotosAlbum({
									filePath: url,
									success: function() {
										uni.showToast({
											title: '图片保存成功',
											icon: 'none',
										})
										bitmap.clear()
									},
								})
							},
							(e) => {
								uni.showToast({
									title: '图片保存失败',
									icon: 'none',
								})
								bitmap.clear()
							}
						)
					},
					(e) => {
						uni.showToast({
							title: '图片保存失败',
							icon: 'none',
						})
						bitmap.clear()
					}
				)
			},
			handleComplete(v = 0) {
				if (v > 0) {
					this.isSign = 0
				}
				uni.showLoading({
					title: '上传中',
				})
				setTimeout(() => {
					signDisclaimer({
						isSign: this.isSign,
						disclaimer: this.myImg,
						number: this.number,
					}).then((r) => {
						if (r.success) {
							// this.$store.commit('setMyAssure', true)
							// let pages = getCurrentPages();
							// let prevPage = pages[pages.length - 2]; //上一个页面
							// prevPage.setData({
							// 	assure: true
							// })
							uni.navigateBack({
								delta: 1,
							})
						}
						uni.hideLoading()
					})
				}, 500)
			},
			getMybase(dataurl) {
				let my = ''
				if (dataurl.split(',')[0].indexOf('base64') >= 0) {
					my = atob(dataurl.split(',')[1])
				} else {
					my = unescape(dataurl.split(',')[1])
				}
				let mime = dataurl.split(',')[0].split(':')[1].split(';')[0]
				let u8arr = new Uint8Array(my.length)

				for (var i = 0; i < my.length; i++) {
					u8arr[i] = my.charCodeAt(i)
				}
				let blob = new Blob([u8arr], {
					type: mime
				})
				this.imgData = blob
				this.getShareImgBase64()
			},
			getShareImgBase64() {
				// const imgData = this.imgData.toDataURL('image/jpeg', 1.0);
				// console.log(imgData,'imgData')
				// this.imgData = imgData
				let baseUrl = ''
				if (process.env.NODE_ENV === 'development') {
					// 开发环境:测试地址
					// #ifndef H5
					baseUrl = httpUrl
					// #endif
					// #ifdef H5
					baseUrl = '/api'
					// #endif
				} else if (process.env.NODE_ENV === 'production') {
					// 生产环境:正式地址
					baseUrl = httpUrl
				}
				let url = baseUrl + '/nurse/order/ossUpload'
				console.log(this.imgData, 'imgData')
				setTimeout(() => {
					uni.uploadFile({
						url: url,
						filePath: _that.imgData,
						// file:tempFiles[0], // 文件
						name: 'file', // 在FormData 中文件对应的属性名
						fileType: 'image',
						// formData: data, // 除文件外其他所有数据，传对象，会默认转换为 FormData
						header: {
							token: _that.$store.state.token,
							contentType: 'multipart/form-data',
						},

						// 不需要手动指定 multipart/form-data ，本 API 默认 multipart/form-data
						// 手动指定需要计算 boundary 并拼接上

						success: (r) => {
							if (r.statusCode == 200) {
								let obj = JSON.parse(r.data)
								console.log(obj)
								_that.myImg = obj.object
								// _that.handleComplete()
							} else {
								console.log(r, '00000')
								uni.showToast({
									icon: 'none',
									title: '操作有误，请重新签名',
								})
							}
						},
						fail: (e) => {
							console.log(e)
							uni.showToast({
								icon: 'none',
								title: '有误',
							})
						},
					})
				}, 3000)
			},
			hideShow() {
				console.log('333')
				// #ifdef MP-WEIXIN
				_that.$refs.pop.hide()
				// #endif
				// #ifdef APP-PLUS || H5
				_that.$nextTick(() => {
					_that.$refs.pop.hide()
				})
				// #endif
			},
			showSign(v) {
				this.type = v
				// #ifdef MP-WEIXIN
				_that.$refs.pop.show()
				// #endif
				// #ifdef APP-PLUS || H5
				_that.$nextTick(() => {
					_that.$refs.pop.show()
				})
				// #endif
			},
			overSign: function() {
				// uni.canvasToTempFilePath({
				// 	canvasId: 'myCanvas',
				// 	success: function(r) {
				// 		//打印图片路径
				// 		console.log(r.tempFilePath)
				// 		console.log('完成签名')
				// 		//设置图片
				// 		_that.myImg = r.tempFilePath;

				// 	}
				// })
				// return

				if (_that.isEnd) {
					uni.canvasToTempFilePath({
						canvasId: 'firstCanvas',
						success: function(res) {
							//打印图片路径
							// console.log(res.tempFilePath)
							// console.log('完成签名')
							//设置图片
							if (_that.type == 2) {
								_that.nurseImage = res.tempFilePath
								return
							}
							_that.getCurrentTime()
							_that.signImage = res.tempFilePath
							// setTimeout(()=> {
							// 		_that.getShareImgBase64().then(r => {
							// 			console.log(r)
							// 			_that.myImg = r
							// 		})
							// }, 1000)
						},
					})
					_that.hideShow()
					_that.clearClick()
				} else {
					uni.showToast({
						title: '请先完成签名',
						icon: 'none',
						duration: 1500,
						mask: true,
					})
				}
			},
			getCurrentTime() {
				//获取当前时间并打印
				var _this = this
				let yy = new Date().getFullYear()
				let mm = new Date().getMonth() + 1
				let dd = new Date().getDate()
				let hh = new Date().getHours()
				let mf =
					new Date().getMinutes() < 10 ?
					'0' + new Date().getMinutes() :
					new Date().getMinutes()
				let ss =
					new Date().getSeconds() < 10 ?
					'0' + new Date().getSeconds() :
					new Date().getSeconds()
				_this.gettime =
					yy + '/' + mm + '/' + dd + ' ' + hh + ':' + mf + ':' + ss
				console.log(_this.gettime)
			},
			// 画布的触摸移动开始手势响应
			start: function(event) {
				// console.log(event)
				// console.log("触摸开始" + event.changedTouches[0].x)
				// console.log("触摸开始" + event.changedTouches[0].y)
				//获取触摸开始的 x,y
				let point = {
					x: event.changedTouches[0].x,
					y: event.changedTouches[0].y,
				}
				// console.log(point)
				touchs.push(point)
			},
			// 画布的触摸移动手势响应
			move: function(e) {
				let point = {
					x: e.touches[0].x,
					y: e.touches[0].y,
				}
				// console.log(point)
				touchs.push(point)
				if (touchs.length >= 2) {
					this.draw(touchs)
				}
			},

			// 画布的触摸移动结束手势响应
			end: function(e) {
				// 设置为已经签名
				this.isEnd = true
				console.log('end')
				// 清空轨迹数组
				touchs.pop()
				// for (let i = 0; i < touchs.length; i++) {
				// 	touchs.pop()
				// }
			},

			// 画布的触摸取消响应
			cancel: function(e) {},

			// 画布的长按手势响应
			tap: function(e) {},
			//画布触摸错误
			error: function(e) {},

			//绘制
			draw: function(touchs) {
				let point1 = touchs[0]
				let point2 = touchs[1]
				touchs.shift()
				//设置线的颜色
				content.setStrokeStyle('#000')
				//设置线的宽度
				content.setLineWidth(5)
				//设置线两端端点样式更加圆润
				content.setLineCap('round')
				//设置两条线连接处更加圆润
				content.setLineJoin('round')
				content.moveTo(point1.x, point1.y)
				content.lineTo(point2.x, point2.y)
				content.stroke()
				content.draw(true)
			},
			//清除操作
			clearClick: function() {
				// 设置为未签名
				this.isEnd = false
				//清除画布
				content.clearRect(0, 0, canvasw, canvash)
				content.draw(true)
			},
		},
	}
</script>
<script lang="renderjs" module="canvasImage">
	import html2canvas from 'html2canvas'
	export default {
		methods: {
			// 生成图片需要调用的方法
			generateImage(e, ownerFun) {
				console.log(1111)
				let _that = this
				setTimeout(() => {
					const dom = document.getElementById('pagePoster')
					console.log(2222) // 需要生成图片内容的 dom 节点
					html2canvas(dom, {
						width: dom.clientWidth, //dom 原始宽度
						height: dom.clientHeight,
						// scrollY: 0, // html2canvas默认绘制视图内的页面，需要把scrollY，scrollX设置为0
						// scrollX: 0,
						useCORS: true, //支持跨域
						// scale: 2, // 设置生成图片的像素比例，默认是1，如果生成的图片模糊的话可以开启该配置项
					}).then((canvas) => {
						console.log(3333)
						console.log(canvas)

						let imgData = canvas.toDataURL('image/png', 0.1);
						// console.log(imgData,'imgData')
						ownerFun.callMethod('getMybase', imgData)

					}).catch(err => {
						console.log(err, 44444)
					});
					// 生成成功
					// html2canvas 生成成功的图片链接需要转成 base64位的url
					// ownerFun.callMethod('receiveRenderData', canvas.toDataURL('image/png'))
				}, 300)
			}
		}
	}
</script>

<style lang="sass">
	.ts color: #FF485D font-size: 30upx height: 100upx line-height: 100upx padding-left: 20upx
	/* .myCanvas{
     width: 100%;
     height:90vh;
	} */
	.firstCanvas background-color: #f2f2f2 width: 100% height: 780rpx
	/* margin: 0 25upx; */
	/* height: calc(100vh - 140upx); */

	.contents
	/* padding-top: 20upx; */
	/* padding-bottom: 100upx; */
	box-sizing: border-box #signatureImg background-color: #EEEEEE .caozuo1 display: flex height: 0 height: constant(safe-area-inset-bottom) height: env(safe-area-inset-bottom) width: 750upx position: fixed left: 0 bottom: 0 background-color: #0599D7 .caozuo display: flex height: 110rpx width: 100% margin-top: 20rpx font-size: 28rpx & view width: 40% text-align: center height: 80rpx line-height: 80rpx color: #FFFFFF margin-left: 5% border-radius: 40rpx & view:last-child width: 40% text-align: center height: 80rpx line-height: 80rpx color: #FFFFFF margin-left: 10% & view:active background-color: #CCCCCC color: #333333 .chongqian background-color: #FFF border: 2rpx solid #3C8EFF color: #3C8EFF !important .over background-color: #3C8EFF .fle display: flex .imgs width: 100% .img width: 100% height: auto .aa position: relative .mybtn
	/* opacity: 0; */
	bottom: 0 position: absolute width: 200rpx height: 100rpx right: 20rpx background-color: red
</style>